package com.yuan.yblog.portal.controller;

import com.yuan.yblog.common.api.CommonResult;
import com.yuan.yblog.common.consts.Constants;
import com.yuan.yblog.portal.aop.annotation.Log;
import com.yuan.yblog.portal.aop.annotation.SlidingWindowLimiter;
import com.yuan.yblog.portal.enums.BusinessType;
import com.yuan.yblog.portal.enums.LimitType;
import com.yuan.yblog.portal.pojo.VO.UserVO;
import com.yuan.yblog.portal.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/user")
@Tag(name = "用户（user）接口")
public class UserController {
    @Autowired
    private UserService userService;

    @Log(title = "更新个人资料", businessType = BusinessType.UPDATE)
    @Operation(summary = "用户更新资料")
    @PutMapping("/setInfo")
    public CommonResult<Integer> update(@Parameter(description = "实体对象") @RequestBody UserVO userVO) {
        boolean succeed = userService.updateUserInfo(userVO);
        if (succeed) {
            return CommonResult.failed();
        } else {
            return CommonResult.success(1,"生效数目：" + 1);
        }
    }

    @SlidingWindowLimiter(key = "user", windowSize = 120, windowTimeRange = 60, limitType = LimitType.IP)
    @Operation(summary = "根据id，获取用户基础资料（非用户本人可获取，敏感信息被抹去）")
    @GetMapping("/getInfo")
    public CommonResult<UserVO> getInfo(@Parameter(description = "用户id") @RequestParam Long userId) {
        UserVO userVO = userService.getUserBasicInfo(userId);
        return CommonResult.success(userVO);
    }

    @Operation(summary = "获取用户自己的详细资料")
    @GetMapping("/getMyInfo")
    public CommonResult<UserVO> getMyInfo() {
        UserVO userVO = userService.getLoginUserInfo();
        return CommonResult.success(userVO);
    }

    @Operation(summary = "用户上传头像")
    @PostMapping("/upload/avatar")
    public CommonResult<String> uploadAvatar(@Parameter(description = "头像文件，大小 <= 1MB" ) @RequestBody MultipartFile file){
        if (file == null) {
            return CommonResult.failed("错误-文件为null");
        }
        boolean succeed = userService.uploadAvatar(file);
        if(succeed) {
            return CommonResult.success("上传成功");
        }
        return CommonResult.failed("上传失败");
    }
}

